package com.tangsm.spring.boot.validation.config;

import com.tangsm.spring.boot.validation.config.filter.RequestFilter;
import com.tangsm.spring.boot.validation.config.interceptor.WebInterceptor;
import com.tangsm.spring.boot.validation.config.property.WhiteListProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;

/**
 * 拦截器配置
 *
 * @author YC
 * @since 2020/9/4
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private WhiteListProperties whiteListProperties;

    @Autowired
    private WebInterceptor webInterceptor;

    /**
     * 配置拦截器
     *
     * @param registry 配置映射拦截器列表对象
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(webInterceptor)
                // 拦截所有
                .addPathPatterns("/**")
                // 放过静态资源
//                .excludePathPatterns("/swagger-resources/**", "/**.html")
                // 忽略URL白名单
                .excludePathPatterns(new ArrayList<>(whiteListProperties.getWhiteList()));
    }

    /**
     * 注册过滤器-RequestFilter
     * <p>此注册方式同等于RequestFilter类上使用以下两个注解：</p>
     * <p>@Component</p>
     * <p>@WebFilter(filterName = "requestFilter", urlPatterns = "/*")</p>
     * @return 过滤器
     */
    @Bean
    public FilterRegistrationBean<RequestFilter> requestFilterRegistrationBean() {
        FilterRegistrationBean<RequestFilter> registration = new FilterRegistrationBean<>();
        // 注册的过滤器
        registration.setFilter(new RequestFilter());
        // 过滤器执行URL
        registration.addUrlPatterns("/*");
        // 注册的名称
        registration.setName("requestFilter");
        // 设置注册bean的顺序（越小权重越大）
        registration.setOrder(-1);
        return registration;
    }
}
